<?php
/**
 * Author  : DAMMAK Wassim
 * Contact : wdammak@talend.com
 * Date    : 12/2008
 * @copyright talend.com 2008
 * @license GNU/GPL Version 2
 **/ 
$maintenance=false;

$nb_occur=3000000;
$time_start = microtime(true);

require_once "includes/configure.php";
require_once "includes/languages/".BABILI_LANG.".php";

require_once "includes/mysql.php";
require_once "includes/user.php";
require_once "includes/acl.php";
require_once "includes/role.php";

// Create the database adapter object (and open/connect to/select db)
$dbMysql = new Mysql(
  DB_SERVEUR,
  DB_USER,
  DB_PASS,
  DB_BDD,
  '',
  true
);
  
$dbMysql->query('SET NAMES UTF8');	
$dbMysql->query('SET CHARACTER SET utf8');

$_SESSION['babili']['dbMysql'] = $dbMysql;

isset($_SESSION['babili']['instance'])?($myAdapter = $_SESSION['babili']['instance']):'';

if( isset($myAdapter) && $myAdapter -> hasIdentity() && isset($_GET["action"]) && $_GET["action"]=="logout" ) {	 
	$myAdapter -> clearIdentity () ;
	unset($_SESSION['babili']);
	//header("Location: ".$_SERVER["SCRIPT_NAME"]);
}

/**
 * Functions
 */
function echo_array($arr){
	echo "<pre>";print_r($arr);echo "</pre>";
}

function echo_time($reset=false){
	global $time_start;
	printf("<p align=\"center\"><span class=\"generatedPage\">".BABILI_PAGE_GEN."</span><br /></p>",(microtime(true)- $time_start));
	if($reset) $time_start=microtime(true);
} 

function fetchArray($query,$key='',$multi=false){

	global $dbMysql;
	
	$return = array();
	
	$result = $dbMysql->query($query);
	
	while ($row = mysql_fetch_assoc($result)){
	
		if($key!=''){
			if($multi)
				$return[$row[$key]][] = $row;
			else
				$return[$row[$key]] = $row;
		}else{
			$return[] = $row;
		}
	
	}
	
	return $return;
}

/*************************************************
//Get All Products
*************************************************/
if(!isset($_SESSION['babili']['products'])){
	$query = "
		SELECT *
		FROM product 
		WHERE status = 'enable'
		ORDER BY id
	";

	$_SESSION['babili']['products'] = $resultProducts = fetchArray($query);
	
}else{

	$resultProducts=$_SESSION['babili']['products'];
	
}

/*************************************************
//Get All Projects
*************************************************/
if(!isset($_SESSION['babili']['projects'])){	
	$query = "
		SELECT proj.*,pp.product_id

		FROM product_project pp
		JOIN product as prod ON prod.id = pp.product_id
		JOIN project as proj ON proj.id = pp.project_id
		
		WHERE prod.status = 'enable' AND proj.status= 'enable'
		
		ORDER BY prod.id, prod.name, proj.name
	";

	$_SESSION['babili']['projects'] = $resultProjects = fetchArray($query, 'product_id' , true);
	
}else{	

	$resultProjects=$_SESSION['babili']['projects'];
	
}

/*************************************************
//Get All langues
*************************************************/
unset($_SESSION['babili']['language']);
if(!isset($_SESSION['babili']['language'])){

	$query =" SELECT * FROM `language`";

	$_SESSION['babili']['language'] = $resultLangues = fetchArray($query, 'id');

}else{

	$resultLangues = $_SESSION['babili']['language'];

}

/**
 * codeAuth: Html Views  
 * Values:
 * 	 => 1  : Identified
 *   => 2  : Maintenance
 *   => 22 : redirect to lost your password (or send email with password)
 *   => 3  : unidentified
 */
$codeAuth=3;

// Check login
if ( !isset($myAdapter) || !$myAdapter -> hasIdentity ( ) ){      	

	if(isset($_POST['username']) ){
		
		$myAdapter = new User($dbMysql,true); //true: Login By Email
		$myAdapter->setIdentity($_POST['username']);
		$myAdapter->setCredential($_POST['passwd']);
		
		$result  =  $myAdapter->authenticate() ;

		if ($result) {
		
			$_SESSION['babili']['instance'] = $myAdapter;
			$_SESSION['babili']['product']  = $_POST['product'];
			
			foreach($resultProducts as $product){
				if($_SESSION['babili']['product']==$product['id']){
					$_SESSION['babili']['productName']=trim($product['label']);
				}
			}
			
			$codeAuth=1;
			
			unset($_SESSION['babili']['keys']);
		
		}else {
			
			
			$getUser = $myAdapter->isExists($_POST['username'],'email');
			
			//Send email with user information.
			if($getUser['email']!=''){
	
				$myAdapter->lostYourPassword();
				
				$codeAuth=22;
			
			//Create new user
			 }else{
			 
				$myAdapter->insert();
				$result  =  $myAdapter -> authenticate () ;
				
				$_SESSION['babili']['instance'] = $myAdapter;
				
				$codeAuth=1;				
			}
		
		}
		 	 
	//Display the login form	 
	}else{
	
		$codeAuth=3;
	
	}

//Already identified
}else{
	
	$codeAuth=1;	

}

//Show guidelines for the first time
if(!isset($_COOKIE['guidelines'])){
 	setcookie("guidelines","yes",time()+(3600*24*30),'/');
	$is_visible_guidelines=true;
}else{
	$is_visible_guidelines=false;
}

/**
 * Output / HTML 
 **/
 
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<!-- Made By D.Wassim : wdammak@talend.com -->
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title><?=BABILI_COMPANY?> Babili<?php if($codeAuth==1): ?> / <?=_PRODUCT?>: <?php echo $_SESSION['babili']['productName']; ?><?php endif;?></title>
	<meta name="description" content="With <?=BABILI_COMPANY?> Babili, Community members can translate the user interface of <?=BABILI_COMPANY?>'s products in any language." />
	<meta name="Author" content="Wassim DAMMAK">
	
	<link rel="stylesheet" href="css/general.css" type="text/css" />
	<?php if($codeAuth!=1): ?>
		<link rel="stylesheet" href="css/cd_login.css" type="text/css" />
	<?php endif; ?>
	<script type="text/javascript" src="js/trans.js"></script>
</head>

<body style="position:relative;">

  <div id="page" style="display:block;">	

	<div id="cacherTout" class="cachediv">&nbsp;<!--[if lte IE 6.5]><iframe></iframe><![endif]--></div>	
<?php 
	
	//<!--Maintenance-->
	if($maintenance==true): 
	
		$codeAuth=2;
		$myAdapter -> clearIdentity () ;
		unset($_SESSION['babili']);	

		echo '	
		<div id="header">';
			include("includes/header.php");
		echo'
		</div>
		
		<div id="main">	
	 		<div class="maintenance">
				<img src="http://www.talend.com/img/style/logo-sources.jpg" align="left" style="padding:10px;" />
				'.BABILI_MAINTENANCE.'
			</div>
		</div>';
	
	//<!--End Maintenance-->
	else:
	 
		  if($codeAuth==1){
				echo '
			<div id="header">';
					require_once("includes/helper.php");
					require_once("includes/header.php"); 
				echo '
			</div>				
			<div id="main">';
				    require_once("includes/main.php");
                echo '
   	 		</div>';
			
		  }else{

		  	if(!isset($_GET["action"]) || (isset($_GET["action"]) && $_GET["action"]!="logout")){
				 unset($_SESSION['babili']);
			 }

		 	echo '
		 	<div id="header">';
				include("includes/header.php");
			echo '
			</div>
			<div id="main">';	
				 // Display error messages: wrong_login
				 if ($codeAuth==2) {
					echo "<center>
							<strong>".BABILI_WRONG_LOGIN."</strong>
						  </center><br/>";
				 }
				 
				 // Display error messages: wrong_password
				 if ($codeAuth==22) {
					echo "<center>
							<strong>
								<span style=\"font-size:16px; color:#FFDF00;\">".BABILI_WRONG_PASSWORD."</span>
							</strong>
						  </center><br/>";
				 }
				 
				 require_once "includes/auth.php";
				 require_once "includes/boards.php";
				 
			echo '	
			</div>';
			}
	endif;
	
	//<!-- Page generated time -->
	echo_time();

	echo '	
	<div id="footer">';
		require_once("includes/footer.php");
	echo '
	</div>';
	
?> 
 </div>
</body>
</html>